//
//  ResourceWindowController.m
//  WebServerTools
//
//  Created by 夏利兵 on 2020/8/28.
//  Copyright © 2020 com.lbx. All rights reserved.
//

#import "ResourceWindowController.h"
#import "GCDWebServer.h"
#import "GCDWebUploader.h"
#import "SJXCSMIPHelper.h"
#import <GCDWebDAVServer.h>
#import <GCDWebServerStreamedResponse.h>
#import <GCDWebServerDataResponse.h>
#import <GCDWebServerDataRequest.h>


#import "LBXFileDownServer.h"
#import "LBXFileUpServer.h"
#import "LBXDAVServer.h"

/*
 https://github.com/swisspol/GCDWebServer
 https://www.jianshu.com/p/6388e5603dca
 */

@interface ResourceWindowController ()<GCDWebUploaderDelegate,GCDWebServerDelegate>
{
//    NSString *_chooseDir;
}

@property (nonatomic, strong) NSString *chooseDir;

//文件下载服务器
//@property (nonatomic, strong) GCDWebServer* webStaticServer;


//发布前端 h5,css,js
//@property (nonatomic, strong) GCDWebServer* releaseFrontEndServer;


//http接口服务器
@property (nonatomic, strong) GCDWebServer* httpServer;
@property (nonatomic, strong) NSArray<NSDictionary*> *echoList;


//文件上传服务器
//@property (nonatomic, strong) GCDWebUploader * webUpLoaderServer;

//DAV服务器，支持trasmit This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using any WebDAV client like Transmit (Mac), ForkLift (Mac) or CyberDuck (Mac / Windows).
//@property (nonatomic, strong) GCDWebDAVServer *webDAVServer;

@property (weak) IBOutlet NSTextField *resourcePath;

@property (weak) IBOutlet NSTextField *listenPort;
@property (weak) IBOutlet NSTextField *httprequestLog;

@property (weak) IBOutlet NSTextField *showIpLabel;
@property (nonatomic, copy) NSString *webStaticServerUrl;

@end

@implementation ResourceWindowController
@synthesize chooseDir = _chooseDir;

- (void)windowDidLoad {
    [super windowDidLoad];
    
    NSString *mainBundleDirectory=[[NSBundle mainBundle] bundlePath];
//    NSString *path=[mainBundleDirectory stringByAppendingPathComponent:@"content.json"];
    NSString *path = [NSString stringWithFormat:@"%@/Contents/Resources/content.json",mainBundleDirectory];
    NSURL *url=[NSURL fileURLWithPath:path];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",dic);
    
    self.window.title = @"mac 服务器";
    
    self.showIpLabel.stringValue = @"点击对应按钮开始服务器，再次点击关闭该服务器";
    
    if (self.chooseDir) {
        self.resourcePath.stringValue = self.chooseDir;
    }
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"httpRequestReponse" ofType:@"plist"];
    //当数据结构为非数组时
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dictionary) {
        [array addObject:dictionary[key]];
    }
    self.echoList = array;
}

- (void)setChooseDir:(NSString *)chooseDir
{
    _chooseDir = chooseDir;

    [self storeWithkey:@"serverResourceDidr" object:chooseDir];
    self.resourcePath.stringValue = chooseDir;
}

- (NSString*)chooseDir
{
    if (_chooseDir) {
        return _chooseDir;
    }
    _chooseDir = [self objetWithKey:@"serverResourceDidr"];
    return _chooseDir;
}

- (NSString*)  deviceAdress
{
    return [SJXCSMIPHelper deviceIPAdress];
}

- (IBAction)chooseDir:(id)sender {
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setMessage:@""];
    [panel setPrompt:@"OK"];
    [panel setCanChooseDirectories:YES];
    [panel setCanCreateDirectories:YES];
    [panel setCanChooseFiles:NO];
    NSString *path_all;
    NSInteger result = [panel runModal];
    if (result == NSFileHandlingPanelOKButton)
    {
        path_all = [[panel URL] path];
        NSLog(@"path:%@", path_all);
        
        self.chooseDir = path_all;
    }
}

- (IBAction)stopAll:(id)sender {
    
//    if (_webStaticServer) {
//        [_webStaticServer stop];
//        self.webStaticServer = nil;
//    }
    
    if (_httpServer) {
        [_httpServer stop];
        self.httpServer = nil;
    }
    
//    if (_releaseFrontEndServer) {
//        [_releaseFrontEndServer stop];
//        self.releaseFrontEndServer = nil;
//    }
//
//    if (_webUpLoaderServer) {
//        [_webUpLoaderServer stop];
//        self.webUpLoaderServer = nil;
//    }
    
//    if (_webDAVServer) {
//        [_webDAVServer stop];
//        self.webDAVServer = nil;
//    }
    
    [[LBXFileDownServer sharedManager]stop];
    [[LBXFileUpServer sharedManager]stop];
    [[LBXDAVServer sharedManager]stop];
}

- (IBAction)startStaticServer:(id)sender
{
    if ([LBXFileDownServer sharedManager].published) {
        
        [[LBXFileDownServer sharedManager]stop];
        return;
    }
    // 文件存储位置
    NSString* downloadsPath = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES) firstObject];
    downloadsPath = [downloadsPath stringByAppendingPathComponent:@"WebServerStore"];
    NSLog(@"文件存储位置 : %@", downloadsPath);
    
    if (self.chooseDir) {
        downloadsPath = self.chooseDir;
    }
    
    NSUInteger port = 8080;
    if (self.listenPort.stringValue && self.listenPort.stringValue.length > 0) {
        port = [self.listenPort.stringValue integerValue];
    }
    
    [LBXFileDownServer sharedManager].port = port;
    
    [LBXFileDownServer sharedManager].fileDir = downloadsPath;
    
    if( [[LBXFileDownServer sharedManager]start])
    {
        self.showIpLabel.stringValue = [[LBXFileDownServer sharedManager]visitUrl];
        
        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
        
        [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
        
        if ([pasteboard setString:self.webStaticServerUrl forType:NSPasteboardTypeString])
        {
            NSLog(@"success");
        }
    }
    else
    {
        self.showIpLabel.stringValue = [LBXFileDownServer sharedManager].errMsg;
    }
}

- (IBAction)releaseStaticResource:(id)sender
{
    [self startStaticServer:sender];
}

- (IBAction)startHttpServer:(id)sender
{
    if (_httpServer) {
        [_httpServer stop];
        self.httpServer = nil;
        self.showIpLabel.stringValue = @"http接口服务器关闭";
        return;
    }
    
    GCDWebServer* webServer = [[GCDWebServer alloc] init];
    
    self.httpServer = webServer;
    
    __weak typeof(self) weakSelf = self;
    
    //    // 文件存储位置
    NSString* downloadsPath = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES) firstObject];
    downloadsPath = [downloadsPath stringByAppendingPathComponent:@"sourceTree/htmlLearn"];
    
    if (self.chooseDir) {
        downloadsPath = self.chooseDir;
    }

    NSLog(@"文件存储位置 : %@", downloadsPath);
    [webServer addGETHandlerForBasePath:@"/" directoryPath:downloadsPath indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
    
    // Add an override handler for all requests to "*.html" URLs to do the special HTML templatization
    [webServer addHandlerForMethod:@"GET" pathRegex:@"/.*\.html" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
        
        NSDictionary* variables = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"variable", nil];
        
        return [GCDWebServerDataResponse responseWithHTMLTemplate:[downloadsPath stringByAppendingPathComponent:request.path]
                                                        variables:variables];
    }];

    [webServer addHandlerForMethod:@"GET" path:@"/request" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) {
        
        //http://192.168.0.107:8080/getDetail?id=id1234567&val=222
        
//        request.query 为url上的参数，不是http body，所有只有get方法  request.query才有可能有参数
        NSLog(@"headers:%@",request.headers);
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:request.query] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:request.query];
                  [responseJMutableJson setValue:@"echo" forKey:@"serverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Get Method paras:%@",request.query];
        });
        return response;
    }];
    
    [webServer addHandlerForMethod:@"GET" path:@"/request1/test1" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) {
        
        //http://192.168.0.107:8080/getDetail?id=id1234567&val=222
        
//        request.query 为url上的参数，不是http body，所有只有get方法  request.query才有可能有参数
        NSLog(@"headers:%@",request.headers);
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:request.query] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:request.query];
                  [responseJMutableJson setValue:@"echo" forKey:@"serverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Get Method paras:%@",request.query];
        });
        return response;
    }];

    [webServer addHandlerForMethod:@"POST" path:@"/request" requestClass:[GCDWebServerDataRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerDataRequest * _Nonnull request) {
        
        NSLog(@"headers:%@",request.headers);
        
        NSDictionary *requestJson  = [self returnDictionaryWithDataPath:request.data];
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:requestJson] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:requestJson];
            [responseJMutableJson setValue:@"echo" forKey:@"macserverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Post Method paras:%@",requestJson];
        });
        
        return response;
    }];
    
    [webServer addHandlerForMethod:@"POST" path:@"/request1" requestClass:[GCDWebServerDataRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerDataRequest * _Nonnull request) {
        
        NSLog(@"headers:%@",request.headers);
        
        NSDictionary *requestJson  = [self returnDictionaryWithDataPath:request.data];
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:requestJson] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:requestJson];
            [responseJMutableJson setValue:@"echo" forKey:@"macserverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Post Method paras:%@",requestJson];
        });
        
        return response;
    }];
    
    [webServer addHandlerForMethod:@"POST" path:@"/request" requestClass:[GCDWebServerDataRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerDataRequest * _Nonnull request) {
        
        NSDictionary *requestJson  = [self returnDictionaryWithDataPath:request.data];
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:requestJson] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:requestJson];
            [responseJMutableJson setValue:@"echo" forKey:@"macserverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Post Method paras:%@",requestJson];
        });
        return response;
    }];
    
    NSUInteger port = 8080;
    
    if (self.listenPort.stringValue && self.listenPort.stringValue.length > 0) {
        port = [self.listenPort.stringValue integerValue];
    }
    
    self.webStaticServerUrl = [NSString stringWithFormat:@"http://%@:%lu/request",[self deviceAdress],(unsigned long)port];
    self.showIpLabel.stringValue = [NSString stringWithFormat:@"%@",self.webStaticServerUrl];
    
    //卡住主线程，适用在 main 控制台应用程序使用
    //    [webServer runWithPort:port bonjourName:@"test"];
    
    
    if( ![webServer startWithPort:port bonjourName:@"test"] )
    {
        self.showIpLabel.stringValue = [NSString stringWithFormat:@"启动失败 端口号：%lu (注意是不是端口被占用了)",(unsigned long)port];
        self.httpServer = nil;
    }
    else
    {
        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];

        [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
        
        if ([pasteboard setString:self.webStaticServerUrl forType:NSPasteboardTypeString])
        {
            NSLog(@"success");
        }
    }
}

- (NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    if (!data) {
        return @{};
    }
    
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    if (!jsonDict) {
        //id=1&pwd=val1 形式字符串
        NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        jsonDict = [self dicByURLParameters:receiveStr];
    }
    
    return jsonDict;
}

#pragma mark - 解析url中的参数，生成NSMutableDictionary

- (NSDictionary *)dicByURLParameters:(NSString *)urlPara {
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 判断参数是单个参数还是多个参数
    if ([urlPara containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [urlPara componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [urlPara componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}


- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}

- (IBAction)startUpLoaderServer:(id)sender
{
    //文件上传服务器
    if ([LBXFileUpServer sharedManager].published) {
        
        [[LBXFileUpServer sharedManager]stop];
        return;
    }
    
    // 文件存储位置
    NSString* downloadsPath = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES) firstObject];
    downloadsPath = [downloadsPath stringByAppendingPathComponent:@"WebServerStore"];
    NSLog(@"文件存储位置 : %@", downloadsPath);
    
    if (self.chooseDir) {
        downloadsPath = self.chooseDir;
    }
    
//    NSUInteger port = 8080;
//    if (self.listenPort.stringValue && self.listenPort.stringValue.length > 0) {
//        port = [self.listenPort.stringValue integerValue];
//    }
//    
//    [LBXFileUpServer sharedManager].port = port;
    
    [LBXFileUpServer sharedManager].fileDir = downloadsPath;
    
    if( [[LBXFileUpServer sharedManager]start] )
    {
        self.showIpLabel.stringValue = [[LBXFileUpServer sharedManager]visitUrl];
        
        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
        [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
        
        if ([pasteboard setString:self.webStaticServerUrl forType:NSPasteboardTypeString])
        {
            NSLog(@"success");
        }
    }
    else
    {
        self.showIpLabel.stringValue = [LBXFileUpServer sharedManager].errMsg;
    }
}

- (IBAction)startDAVServer:(id)sender
{
    if ([LBXDAVServer sharedManager].published) {
        
        [[LBXDAVServer sharedManager]stop];
        return;
    }
    
    // 文件存储位置
    NSString* downloadsPath = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES) firstObject];
    downloadsPath = [downloadsPath stringByAppendingPathComponent:@"WebServerStore"];
    NSLog(@"文件存储位置 : %@", downloadsPath);
    
    if (self.chooseDir) {
        downloadsPath = self.chooseDir;
    }
    
    NSUInteger port = 8080;
    if (self.listenPort.stringValue && self.listenPort.stringValue.length > 0) {
        port = [self.listenPort.stringValue integerValue];
    }
    
    [LBXDAVServer sharedManager].port = port;
    
    [LBXDAVServer sharedManager].fileDir = downloadsPath;
    
    if( [[LBXDAVServer sharedManager]start] )
    {
        self.showIpLabel.stringValue = [[LBXDAVServer sharedManager]visitUrl];
        
        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
        
        [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
        
        if ([pasteboard setString:self.webStaticServerUrl forType:NSPasteboardTypeString])
        {
            NSLog(@"success");
        }
    }
    else
    {
        self.showIpLabel.stringValue = [LBXDAVServer sharedManager].errMsg;
    }
}



#pragma mark - <GCDWebServerDelegate>
/**
 *  This method is called after the server has successfully started.
 */
- (void)webServerDidStart:(GCDWebServer*)server
{
//
    if (server.running) {
        self.showIpLabel.stringValue = [NSString stringWithFormat:@"服务器启动成功 url:%@",server.serverURL.absoluteString];

    }
}


#pragma mark - <GCDWebUploaderDelegate>
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
    NSLog(@"[UPLOAD] %@", path);
    
//    self.showIpLabel.hidden = YES;
    
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSLog(@"%@",[fileManager contentsOfDirectoryAtPath:string error:nil]);
    
//    self.fileArray = [NSMutableArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:string error:nil]];
    
//    [self.fileTableView reloadData];
}

- (void)webUploader:(GCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
    NSLog(@"[MOVE] %@ -> %@", fromPath, toPath);
}

- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path {
    NSLog(@"[DELETE] %@", path);
    
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
     NSLog(@"%@",[fileManager contentsOfDirectoryAtPath:string error:nil]);
//    self.fileArray = [NSMutableArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:string error:nil]];
//    
//    [self.fileTableView reloadData];
}

- (void)webUploader:(GCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path {
    NSLog(@"[CREATE] %@", path);
}


#pragma mark- store

- (void)storeWithkey:(NSString*)key object:(id)object
{
    [[NSUserDefaults standardUserDefaults]setObject:object forKey:key];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (id)objetWithKey:(NSString*)key
{
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}

@end
